<?php

namespace Frieza\Modules\Activity\Controllers;

use App\Pockets\GridDataModel as pGridDataModel;
use Biz\cache\advertisement\CActivitySpotlightPN;
use Biz\service\activity\ServeActivityArchive;
use Biz\service\advertisement\spotlight\SpotlightActivityService;
use Biz\service\advertisement\spotlight\SpotlightConfig;
use Doraemon\pockets\constInterface\LinkConf;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\LinkFormat;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Displayers\DropdownActions;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Frieza\Modules\Activity\Actions\ArchiveCache;
use Frieza\Modules\Activity\Actions\ClearFeaturesCache;
use Frieza\Modules\Activity\Actions\ClearGuessCache;
use Frieza\Modules\Activity\Actions\ClearNextSubscribeCache;
use Frieza\Modules\Activity\Actions\ClearOpenCache;
use Frieza\Modules\Activity\Actions\ClearSubscribeCache;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class SpotlightController
{


    private $listRoute = '';

    public function __construct()
    {
        $this->listRoute = admin_url('/activity/Spotlight/list');
    }

    private function getId($id): string
    {
        return SpotlightConfig::getId($id);
    }

    public function clearCache($id, $action)
    {
        try {
            $content = '清除成功';
            if (empty($id)) throw new \Exception('id为空');
            if (empty($action)) throw new \Exception('非法操作');
            $activity = SpotlightActivityService::getActivity($id);
            $cache = $activity->getCacheHandler();
            switch ($action) {
                case 'subscribe':
                    $cache::clearSubscribe();
                    break;
                case 'guess':
                    $cache::clearGuess();
                    $cache::clearRanking();
                    break;
                case 'open':
                    $cache::clearOpen();
                    break;
                case 'features':
                    $cache::clearLikeFeatures();
                    break;
                case 'nextSubscribe':
                    $cache::clearNextSubscribe();
                    $cache::clearLog();
                    break;
                case 'archive':
                    $data = $this->getCreateData($id);
                    $end_time = $data['end_time'] ?? '';
                    if (empty($end_time)) throw new \Exception('活动未结束');
                    //归档操作
                    $allCache = $activity->allCache();
                    $content = '归档成功';
                    ServeActivityArchive::getInstance()->clearArchive(ServeActivityArchive::SPOTLIGHT_ACTIVITY_ID, $id);
                    foreach ($allCache as $key => $cache) {
                        ServeActivityArchive::getInstance()->saveArchive(ServeActivityArchive::SPOTLIGHT_ACTIVITY_ID, $id, $key, $cache);
                    }
                    //清除缓存
                    $activity->clearAllCache();
                    break;
                default:
                    throw new \Exception('未定义操作');
            }

            $type = 'success';
        } catch (\Exception $e) {
            $type = 'error';
            $content = $e->getMessage();
        }
        $result = [
            'status' => true,
//            'then'   => [
//                'action' => 'refresh',
//                'value'  => true,
//            ],
            'toastr' => [
                'type'    => $type,
                'content' => $content,
            ]
        ];

        return response()->json($result);
    }

    public function main(Content $content, Request $request)
    {
        $list = CActivitySpotlightPN::allConfig();
        $data = [];
        $hasArchive = ServeActivityArchive::getInstance()->hasArchive(ServeActivityArchive::SPOTLIGHT_ACTIVITY_ID);
        foreach ($list as $v) {
            $temp = json_decode($v, true);
            $temp['created_at_date'] = date("Y-m-d H:i:s", $temp['created_at']);
            $link = $temp['id'] > 3 ? "/activity/spot-light/reserve" : "/brand/spot-light/reserve";
            $pubLink = $temp['id'] > 3 ? "/activity/spot-light/publish" : "/brand/spot-light/publish";
            $temp['_link'] = Hhzurl::getDomain() . "$link?stage=" . $temp['id'];
            $temp['_pub_link'] = Hhzurl::getDomain() . "$pubLink?stage=" . $temp['id'];
            $temp['hasArchive'] = !empty($hasArchive[$temp['id']]);
            $data[] = $temp + ['_subscribe' => '点击查看'];
            $sort[] = $temp['id'];
        }
        if ($data) array_multisort($sort, SORT_DESC, $data);

        $gridModel = new pGridDataModel($data, CActivitySpotlightPN::totalConfig());
        $grid = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableFilter();
                $grid->disablePagination();
                $grid->setActionClass(DropdownActions::class);
                $grid->paginate($gridModel->getPerPage());
                $grid->column('id', '记录id')->width(80);
                $grid->column('name', '活动名称')->width(200);
                $grid->column('_link', '预约页面')->display(function () {
                    return '';
                })->copyable()->qrcode(function($v){
                    return urlencode(json_encode(
                        [
                            'type' => 'link',
                            'link' => LinkFormat::generateSingleLink(LinkConf::LINK_APP_FULLSCREEN, ['url' => $v])
                        ]
                    ));
                })->width(100);
                $grid->column('_pub_link', '发布页面')->display(function () {
                    return '';
                })->copyable()->qrcode(function($v){
                    return urlencode(json_encode(
                        [
                            'type' => 'link',
                            'link' => LinkFormat::generateSingleLink(LinkConf::LINK_APP_FULLSCREEN, ['url' => $v])
                        ]
                    ));

                })->width(100);
                $grid->column('release_time', '发布时间')->width(150);
                $grid->column('end_time', '活动结束时间')->width(150);
                $grid->column('created_at_date', '创建时间')->width(150);
                $grid->column('_subscribe', '统计数据')->modal('数据', SpotlightCache::class)->width(100);
                $grid->column('admin_id', '操作人')->display(function () {
                    return $this->admin_id ? Admin::user()->find($this->admin_id)->name : '-';
                })->width(100);
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                    $actions->disableView();
                    $actions->add(new ClearSubscribeCache());
                    $actions->add(new ClearGuessCache());
                    $actions->add(new ClearOpenCache());
                    $actions->add(new ClearFeaturesCache());
                    $actions->add(new ClearNextSubscribeCache());
                    if(!$actions->row->hasArchive && $actions->row->end_time && $actions->row->end_time < date("Y-m-d H:i:s")) $actions->add(new ArchiveCache());
                });

            }
        );
        return $content
            ->header('新品聚光灯列表')
            ->row($grid)
            ;
    }

    public function delete($id)
    {
        $status = true;
        $message = "删除成功";
        try {

            CActivitySpotlightPN::delConfig($id);

        } catch (\Exception $e) {
            $status = false;
            $message = "操作失败,信息:" . $e->getMessage();
        }

        return response()->json(compact('status', 'message'));
    }

    public function save(Request $request)
    {
        try {
            $all = $request->all();
            $spotlight = $all['spotlight'] ?? [];
            if (empty($spotlight)) throw new \Exception('数据为空');
            $spotlight['created_at'] = time();
            $spotlight['admin_id'] = Admin::user()->id;
            $id = $spotlight['id'] ?: (CActivitySpotlightPN::totalConfig() + 1);
            $spotlight['id'] = $id;
            $success = new MessageBag([
                'title' => ($id > 0 ? '编辑' : '添加') . '成功'
            ]);
            $old = CActivitySpotlightPN::getConfig($this->getId($id));
            $old = empty($old) ? [] : json_decode($old, true);
            CActivitySpotlightPN::setConfig($this->getId($id), json_encode($spotlight + $old, JSON_UNESCAPED_UNICODE));
            return redirect($this->listRoute)->with(compact('success'));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '操作失败,信息:' . $e->getMessage()
            ]);
            return back()->withInput()->with(compact('error'));
        }

    }

    public function create(Request $request, Content $content, $id = 0)
    {
        //创建表单
        $info = $this->getCreateData($id);
        $form = $this->createForm($info);
        $header = ($id > 0 ? '编辑' : '添加') . '新品聚光灯';
        return $content->header($header)->description(' ')
            ->breadcrumb(
                ['text' => '新品聚光灯列表', 'url' => $this->listRoute],
                ['text' => $header]
            )
            ->row($form);
    }

    private function getCreateData($id)
    {
        return json_decode(CActivitySpotlightPN::getConfig($this->getId($id)), true);
    }

    private function createForm($info): Form
    {
        $input['spotlight'] = $info;
        $form = new Form($input);
        $form->action(admin_url('/activity/Spotlight/list/save'));
        $form->disableReset();
        $form->hidden('spotlight.id');
        $form->text('spotlight.name', '页面名称')->required();
        $form->text('spotlight.brand_id', '品牌id')->required();
        $form->datetime('spotlight.release_time', '倒计时结束时间');
        $form->datetime('spotlight.end_time', '活动结束时间')->help("活动结束后,删除的数据将归档");
        $form
        ->radioCard("check", '页面选择')
        ->options(['预约页面', '发布页面'])
        ->default(0)
        ->when(0, function (Form $form) {
                $form->text('spotlight.share_title', '分享标题');
                $form->text('spotlight.share_msg', '分享摘要');
                $form->imgUpload('spotlight.share_img', '分享图');
                $form->text('spotlight.bg_color', '页面背景色')->help('1个6位色值');
                $form->imgUpload('spotlight.main_pic', '头图');
                $form->imgUpload('spotlight.brand_bg_img', '品牌背景图');
                $form->text('spotlight.brand_name_color', '品牌名称色值')->help('1个6位色值');
                $form->text('spotlight.brand_unfav_color', '关注色值')->help('1个6位色值');
                $form->text('spotlight.brand_fav_color', '已关注色值')->help('1个6位色值');
                $form->imgUpload('spotlight.box_pic', '盲盒图', true)->help('盲盒图顺序:框框,蒙版,背景+光晕,盲盒,提交猜一猜后结果展示的背景,盲盒预约按钮');
                $form->textarea('spotlight.labels', '线索文案')->help('换行分隔');
                $form->imgUpload('spotlight.guess_pic', '新品猜一猜切图', true)->help('猜一猜切图顺序:文字切图,说明文案切图,猜一猜按钮选中小图标,猜一猜确认按钮,猜一猜分享按钮,提交按钮下文字切图');
                $form->textarea('spotlight.guess', '猜一猜选项')->help('换行分隔');
                $form->textarea('spotlight.guess_rank', '猜一猜结果')->help('换行分隔,在填写结果中按照投票比例从大到小选择前5项');
                $form->text('spotlight.guess_color', '猜一猜选项未选中颜色')->help('2个6位色值，英文逗号分隔; 实例 D3B892,D3B892');
                $form->text('spotlight.guess_selected_color', '猜一猜选项选中颜色')->help('2个6位色值，英文逗号分隔; 实例 D3B892,D3B892');
                $form->text('spotlight.guess_result_color', '猜一猜结果按钮颜色')->help('3个6位色值，前2个色值位按钮颜色，第3个色值为按钮阴影颜色');
                $form->imgUpload('spotlight.prepare_other_pic', '预约页末尾切图', true)->help('顺序:活动说明文案切图,末尾切图');
                $form->text('spotlight.guess_prepare_statsign', '预约页标识符');
        })->when(1, function (Form $form) {
                $form->text('spotlight.publish_share_title', '分享标题');
                $form->text('spotlight.publish_share_msg', '分享摘要');
                $form->imgUpload('spotlight.publish_share_img', '分享图');
                $form->text('spotlight.publish_bg_color', '页面背景色')->help('1个6位色值');
                $form->imgUpload('spotlight.publish_bg_pic', '页面背景图');
                $form->imgUpload('spotlight.publish_main_pic', '头图');
                $form->imgUpload('spotlight.publish_brand_bg_pic', '品牌号背景');
                $form->text('spotlight.publish_brand_name_color', '品牌名称色值')->help('1个6位色值');
                $form->text('spotlight.publish_brand_unfav_color', '关注色值')->help('1个6位色值');
                $form->text('spotlight.publish_brand_fav_color', '已关注色值')->help('1个6位色值');
                $form->imgUpload('spotlight.publish_box_pic', '盲盒图', true)->help('顺序:框,蒙版,盲盒,背景,盲盒打开按钮');
                $form->imgUpload('spotlight.publish_product_pic', '产品图', true)->help('顺序:产品图,想买背景框,想买按钮,已想买按钮');
                $form->text('spotlight.wiki_title', '商品名称');
                $form->text('spotlight.wiki_price', '商品价格');
                $form->text('spotlight.wiki_id', '商品id');
                $form->imgUpload('spotlight.publish_barrage_pic', '弹幕图', true)->help('顺序:弹幕框框末端样式左,弹幕框框末端样式右');
                $form->textarea('spotlight.barrage', '弹幕内容')->help('换行分隔');
                $form->text('spotlight.publish_barrage_color', '弹幕背景色')->help('1个6位色值');
                $form->imgUpload('spotlight.publish_video_pic', '视频图', true)->help('顺序:视频标题切图,视频封面图');
                $form->text('spotlight.video', '视频地址');
                $form->imgUpload('spotlight.publish_note_pic', '大咖说图', true)->help('顺序:大咖说标题切图,大咖说图片(多图)');
                $form->text('spotlight.publish_note', '大咖说跳转id')->help('数量与图保持一致');
                $form->imgUpload('spotlight.publish_buy_pic', '新品抢先购图', true)->help('顺序:标题切图,商品卡片切图');
                $form->text('spotlight.wiki_link', '商品h5链接')->help('非必填（如填写，新品抢先购跳h5）');
                $form->imgUpload('spotlight.publish_room_pic', '直播切图');
                $form->text('spotlight.room_id', '直播房间id');
                $form->imgUpload('spotlight.publish_features_pic', '新品打call图', true)->help('顺序:大标题切图,小标题切图,背景图上,背景图下,选中图标');
                $form->textarea('spotlight.features', '新品打call站选项')->help('换行分隔');
                $form->text('spotlight.features_bg_color', '新品打call站背景色')->help('2个6位色值，英文逗号分隔; 实例 D3B892,D3B892');
                $form->text('spotlight.features_unselected_color', '新品打call站按钮未选中颜色')->help('2个6位色值，英文逗号分隔; 实例 D3B892,D3B892');
                $form->text('spotlight.features_selected_color', '新品打call站按钮选中颜色')->help('2个6位色值，英文逗号分隔; 实例 D3B892,D3B892');
                $form->imgUpload('spotlight.publish_award_pic', '兑奖图', true)->help('顺序:兑奖标题切图,兑奖上期名单背景切图,兑奖说明文案切图,预约下期按钮未点击切图,预约下期按钮点击切图');
                $form->text('spotlight.winners', '中奖名单')->help('英文逗号分隔');
                $form->imgUpload('spotlight.publish_pool_img', '瀑布流标题切图');
                $form->imgUpload('spotlight.publish_button_img', '发布按钮切图');
                $form->text('spotlight.topic_id', '话题id');
                $form->text('spotlight.publish_statsign', '发布页标识符');
                $form->text('spotlight.publish_wiki_statsign', 'wiki标识符');
                $form->text('spotlight.publish_note_statsign', '瀑布流note标识符');
        });

        return $form;
    }


}